package com.hx.houtai.config;

import com.hx.houtai.util.JwtUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr.Fang
 * @Title: JwtAuthenticationFilter
 * @Package hx
 * @Description: jwt配置文件
 * @date 2021/3/4 20:31
 */

@Configuration
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final PathMatcher pathMatcher = new AntPathMatcher();
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //跨域
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token, content-type"); //这里要加上content-type
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        try {

            if (httpServletRequest.getMethod().equals("OPTIONS")) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            } else {
                if (isProtectedUrl(httpServletRequest)) {
                    //因为jwt用来验证身份的验证码是储存在header中的，而用swagger2时header中的值不好设置，需要进行修改，因此这里改成了从body中获取
                    String token = httpServletRequest.getHeader("Authorization");
//                String token = request.getParameter("Authorization");
                    //检查jwt令牌, 如果令牌不合法或者过期, 里面会直接抛出异常, 下面的catch部分会直接返回
                    JwtUtil.validateToken(token);
                }
            }
        }catch (Exception e){
            httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"token验证失败！");
            httpServletResponse.setStatus(401);
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    public static boolean isProtectedUrl(HttpServletRequest request){
        return pathMatcher.match("/FL/**",request.getServletPath());
    }
}
